package com.starblink.message.messagefollower.ui

import androidx.lifecycle.lifecycleScope
import com.alibaba.android.arouter.facade.annotation.Route
import com.starblink.basic.route.RoutePage
import com.starblink.android.basic.base.activity.BaseTVMActivity
import androidx.recyclerview.widget.LinearLayoutManager
import com.starblink.android.basic.bean.LoadAction
import com.starblink.basic.apollo.ext.ApolloValSetExt.apolloValue
import com.starblink.android.basic.modules.mine.MineManager
import com.starblink.android.basic.util.bus.FlowBus
import com.starblink.android.basic.util.bus.FlowConst
import com.starblink.android.basic.util.bus.bean.FollowUserEvent
import com.starblink.basic.log.SKLogger
import com.starblink.basic.style.title.OnTitleBarListener
import com.starblink.basic.style.title.TitleBar
import com.starblink.message.R
import com.starblink.message.databinding.ActivityMessageFollowerBinding
import com.starblink.message.messagelikeorcomment.adapter.MessageFollowerAdapter
import kotlinx.coroutines.launch

/**
 * 关注消息页
 */
@Route(path = RoutePage.Message.MESSAGE_FOLLOWERS)
class MessageFollowerActivity :
    BaseTVMActivity<ActivityMessageFollowerBinding, MessageFollowerVM>() {
    private val mAdapter = MessageFollowerAdapter()

    override fun initViewBinding(): ActivityMessageFollowerBinding =
        ActivityMessageFollowerBinding.inflate(layoutInflater)


    override fun initView() {
        super.initView()
        viewBinding.titleBar.setOnTitleBarListener(object : OnTitleBarListener {
            override fun onLeftClick(titleBar: TitleBar?) {
                finish()
            }
        })

        viewBinding.recyclerView.layoutManager = LinearLayoutManager(this)
        viewBinding.recyclerView.setHasFixedSize(true)
        viewBinding.recyclerView.itemAnimator = null
        viewBinding.recyclerView.adapter = mAdapter
        mAdapter.setEmptyViewLayout(this, R.layout.layout_empty_view_message)
        mAdapter.isEmptyViewEnable=false

        viewBinding.smartRefreshLayout.setEnableAutoLoadMore(true)
        viewBinding.smartRefreshLayout.setOnRefreshListener {
            viewModel.getUserMessageList(refresh = true)
        }
        viewBinding.smartRefreshLayout.setOnLoadMoreListener {
            viewModel.getUserMessageList(refresh = false)
        }

        // 点击Item
        mAdapter.setOnItemClickListener() { adapter, view, position ->
            adapter.getItem(position)?.friend?.let {
                MineManager.navigationToOtherUserPersonHome(
                    mContext,
                    accountId = it.id,
                    accountDeleted = it.deleted,
                    userName = it.username ?: it.userName
                )
            }
        }
    }

    override fun initObservable() {
        super.initObservable()
        initFlowEvents()

        viewModel.listResponseLiveData.observe(this)
        {
            if (mAdapter.items.isEmpty() || it.refresh) {
                SKLogger.e("dss", "mAdapter.items.isEmpty() || it.refresh")
                // 刷新或页面销毁恢复
                mAdapter.submitList(ArrayList(it.totalList))
                if (it.totalList.size < viewModel.curPageNo * MessageFollowerVM.PAGE_SIZE) {
                    SKLogger.e("dss", "LoadAction.setNoMoreData")
                    viewBinding.smartRefreshLayout.setNoMoreData(true)
                }
            } else {
                // 加载更多
                SKLogger.e("dss", "加载更多")
                mAdapter.addAll(it.pageList)
                if (it.pageList.size < MessageFollowerVM.PAGE_SIZE) {
                    SKLogger.e("dss", "LoadAction.setNoMoreData")
                    viewBinding.smartRefreshLayout.setNoMoreData(true)
                }
            }
        }
        viewModel.mLoadActionLiveData.observe(this) {
            when (it.action) {
                LoadAction.STATE_SUCCESS, LoadAction.STATE_ERROR -> {
                    if (viewBinding.smartRefreshLayout.isRefreshing) {
                        viewBinding.smartRefreshLayout.finishRefresh()
                        if (it.action == LoadAction.STATE_SUCCESS) {
                            // 仅刷新成功时，重置状态
                            viewBinding.smartRefreshLayout.resetNoMoreData()
                            mAdapter.isEmptyViewEnable = true
                        }
                    } else if (viewBinding.smartRefreshLayout.isLoading) {
                        viewBinding.smartRefreshLayout.finishLoadMore()
                    }
                }
            }
        }
    }

    override fun initLoad() {
        super.initLoad()
        viewBinding.smartRefreshLayout.autoRefresh()
    }

    private fun initFlowEvents() {
        FlowBus.with<FollowUserEvent>(FlowConst.FOLLOW_USER_EVENT).register(this) {
            if(it.id.isNullOrEmpty()) return@register
            SKLogger.e("dss", "MessageFollowerActivity-FOLLOW_USER_EVENT")
            // 关注事件，用户列表更新状态
            if(viewModel.listResponseLiveData.value != null){
                lifecycleScope.launch {
                    for ((index, userMessage) in viewModel.listResponseLiveData.value!!.totalList.withIndex()) {
                        val accountF = userMessage.friend
                        if (it.id == accountF.id && it.relationCode != accountF.relationCode) {
                            SKLogger.e("dss", "MessageFollowerActivity列表发现用户关注状态要修改")
                            accountF.apolloValue("relationCode", it.relationCode)
                            mAdapter.notifyItemChanged(index)
                            break
                        }
                    }
                }
            }
        }
    }
}